﻿namespace PortableRiotGames.Infrastructure.Converters
{
    using Newtonsoft.Json;
    using System;

    public class JsonGameTypeConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value.ToString() == "CUSTOM_GAME") return GameType.Custom;
            if (reader.Value.ToString() == "MATCHED_GAME") return GameType.Matched;
            if (reader.Value.ToString() == "CO_OP_VS_AI_GAME") return GameType.CoopVsAI;
            if (reader.Value.ToString() == "TUTORIAL_GAME") return GameType.Tutorial;
            return GameType.Custom;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var gameType = (GameType)(Enum.Parse(typeof(GameType), value.ToNullableString()));

            var valueToSerialize = string.Empty;

            if (gameType == GameType.Custom) valueToSerialize = "CUSTOM_GAME";
            else if (gameType == GameType.Matched) valueToSerialize = "MATCHED_GAME";
            else if (gameType == GameType.CoopVsAI) valueToSerialize = "CO_OP_VS_AI_GAME";
            else if (gameType == GameType.Tutorial) valueToSerialize = "TUTORIAL_GAME";

            serializer.Serialize(writer, valueToSerialize);
        }
    }
}
